<template>
  <!--页面上边距=状态栏+顶部搜索栏(40)-->
  <div id="home-page" :style="{top:(0)+'px'}">

    <!--顶部搜索栏-->
    <div id="search-box" :style="{width:topMaxWidth,top:(this.getSafeArea().top)+'px'}">
      <div id="change-city" @click="changeCity()">
        <i class="el-icon el-icon-location"></i>
        <span class="ovd_s" v-text="CurrUser.City"></span>
      </div>
      <div id="search-input-outer">
        <!--        <i class="search-bar-logo"></i>-->
        <i class="icon iconfont icon-sousuo"></i>
        <input type="text" readonly="true" @click="$router.push('/SearchAct?fromType=Home')" class="search-bar-input" placeholder="搜索你想要的商品...">
<!--        <get-product-name-by-image/>-->
        <div class="c"></div>
      </div>
      <div id="qr-button">
        <qr-scan/>
      </div>
      <div class="c"></div>
    </div>

    <!--轮播图-->
    <div class="swiper-banner" style="position: relative;" :style="{top:(this.getSafeArea().top+40)+'px'}">
      <div class="swiper-wrapper" v-if="bannerArr.length>0">
        <div class="swiper-slide" v-for="(item,key) in bannerArr" :key="key">
          <img class="home-banner-image" :src="item.image"
               @click="bannerTurn(item)">
        </div>
      </div>
      <div class="swiper-pagination"></div><!--分页器。如果放置在swiper外面，需要自定义样式。-->
    </div>

    <div id="active-box" style="position: relative;" :style="{top:(this.getSafeArea().top+45)+'px'}">
      <div class="item" v-for="(item,index) in activeList" @click="$router.push(item.url)" v-if="isShowItem(item,index)">
        <div class="icon-box">
          <img :src="item.imageUrl"/>
        </div>
        <span v-text="item.name"></span>
      </div>
      <div class="c"></div>
    </div>

    <div class="shop-box" style="position: relative;" :style="{top:(this.getSafeArea().top+45)+'px'}">
      <div class="item">
        <i class="more-icon iconfont icon-jinrujiantouxiao"></i>
        <div class="title-box">
          <span class="title">品牌列表</span>
          <span class="sub-title"></span>
        </div>
        <div class="shop-brand-list" @click="$router.push('/ProductBrand')">
          <div class="item" v-for="(brandItem,index) in tmpBrandList" v-if="brandList.length===0">
            <img :src="brandItem.image" width="100%" alt="">
          </div>
          <div class="item" v-for="(brandItem,index) in brandList" v-if="brandList.length>0">
            <img :src="brandItem.image" width="100%" alt="">
          </div>
          <div class="c"></div>
        </div>
      </div>
      <div class="item">
        <i class="more-icon iconfont icon-jinrujiantouxiao"></i>
        <div class="title-box">
          <span class="title">商家列表</span>
<!--          <span class="sub-title">天天低价</span>-->
        </div>
        <div class="shop-list" @click="$router.push('/SearchResultShop?act=getList&distance='+dict.NearlyShopDistance)">
          <div class="big-icon">
            <img :src="'static/brand-icon/shop-nums.png'" width="100%" alt="">
          </div>
          <div class="shop-nums">
            <div class="title">
              当前城市<span class="num" v-text="shopNums"></span>商家
              <br>
              <a href="javascript:void(0)">立即查看</a>
            </div>
          </div>
          <div class="c"></div>
        </div>
      </div>
      <div class="c"></div>
    </div>

    <div style="position: relative; top: 45px; padding-bottom: 60px;">
      <product-list-item :index="index" :key="index" :show-type="0" :curr-product="item" v-for="(item,index) in productList"></product-list-item>
      <div class="c"></div>
    </div>
    <div class="c"></div>

  </div>
</template>

<script>
import ProductListItem from '../common/ProductListItem'
import QrScan from '../common/QrScan'
import md5 from 'js-md5'
import IScrollerBox from '../common/IScrollerBox'
import GetProductNameByImage from '../common/GetProductNameByImage'

export default {
  name: 'Home',
  components: {GetProductNameByImage, IScrollerBox, QrScan, ProductListItem},
  beforeMount () {
    // this.addVisitLog()
  },
  destroyed () {
    window.onscroll = null
  },
  data () {
    return {
      productListLoading:false,
      productListMore:true,
      shopNums: 0,
      brandList:[],
      tmpBrandList: [
        {
          name: '公牛',
          image: 'https://duosahngzhao.oss-cn-zhangjiakou.aliyuncs.com/2021/12/4d48cfc018f74123baf4994d0223d6da.jpg'
        },
        {
          name: '正泰电器',
          image: 'https://duosahngzhao.oss-cn-zhangjiakou.aliyuncs.com/2021/12/742ef202933c4a109ade9f5dd4e3da06.png'
        },
        {
          name: '德力西电气',
          image: 'https://duosahngzhao.oss-cn-zhangjiakou.aliyuncs.com/2021/12/598363ba13224613b006c632d372fc8e.png'
        },
      ],
      activeList: [
        {name: '热销商品', url: '/ProductNew', imageUrl: 'static/home-icon/xinpintuijian.png'},
        {name: '优惠团购', url: '/ProductGroup', imageUrl: 'static/home-icon/youhuituangou.png'},
        {name: '抢购活动', url: '/ProductSeckill', imageUrl: 'static/home-icon/xianshimiaosha.png'},
        {name: '领券中心', url: '/Coupon', imageUrl: 'static/home-icon/lingquanzhongxin.png'},
        {name: '入驻平台', url: '/SubmitShopApply', imageUrl: 'static/home-icon/ruzhupingtai.png'},
        // {name: '使用帮助', url: '/UseHelp', imageUrl: 'static/home-icon/ruzhupingtai.png'},
      ],
      isSkill:0,
      bannerArr: [
        // {type: 'product', image: './static/images/banner-1.jpg'},
        // {type: 'product', image: './static/images/banner-2.jpg'},
        // {type: 'product', image: './static/images/banner-3.jpg'},
      ],
      productCateList: window.demoData.productCateList,
      productList: [],
      topMaxWidth: ''
    }
  },
  mounted () {
    let $this=this
    window.onscroll=function(){
      // console.log(event);
      var maxY=document.documentElement.offsetHeight-document.documentElement.clientHeight
      // console.log('document.documentElement.clientHeight: ',document.documentElement.clientHeight)
      // console.log('document.documentElement.offsetHeight: ',document.documentElement.offsetHeight)
      // console.log('document.documentElement.scrollHeight: ',document.documentElement.scrollHeight)
      if (maxY-window.scrollY<=200){
        $this.getProductList()
      }
      // console.log('window.scrollY: ',window.scrollY)
    };

    // api.toast({
    //   msg:'状态栏高度: '+this.getSafeArea().top+'px'
    // })
    var winSize = this.getWinSize()
    if (winSize.width > 1024) {
      this.topMaxWidth = '375px'
    }
    // alert(JSON.stringify(winSize))
    this.productListMore=true
    this.getProductList()
    this.getHomeData()
  },
  methods: {
    isShowItem(item,index){
      if ((this.isSkill===0 && index===2) || index===0){
        return false
      }
      return true
    },
    joinTest:function (orderNo) {
      let $this=this
      $this.MyRequest($this.ApiDoNameMember + 'Member/getShopProductPurchaseList', {orderNo: orderNo}, function (data) {
        // console.log('data',data)
        $this.$confirm('系统已经匹配到【采购订单】您是否前往提交?', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          var shopProductPurchaseOrder = {}
          if (data.list && data.list.length > 0) {
            shopProductPurchaseOrder = data.list[0]
          } else {
            return $this.successTip('采购订单不存在!', 'error')
          }
          // [{"image":"http://image.yangfankj.com/product/103/0.jpg","price":215.00,"name":"德国欧莱德-磨角机","model":"常规","id":8,"nums":1},{"image":"http://image.yangfankj.com/product/105/0.jpg","price":195.00,"name":"东成-气动直钉枪","model":"常规","id":11,"nums":5}]
          var tmpProductList = shopProductPurchaseOrder.productData
          var confirmOrderData = {
            shop: {
              id: shopProductPurchaseOrder.shopId,
              name: shopProductPurchaseOrder.shopName,
              logo: shopProductPurchaseOrder.shopLogo,
            },
            productList: []
          }
          tmpProductList.forEach(function (product, index) {
            confirmOrderData.productList.push({
              id: product.shopProductStockId,
              shopProductId: product.id,
              shopProductName: product.name,
              price: product.price,
              image: product.image,
              model: product.model,
              nums: product.nums
            })
          })

          // 存储: 店铺数据,商品数据
          localStorage.setItem('selectProductData', JSON.stringify(confirmOrderData))
          // 跳转至-订单确认页面
          $this.$router.push({
            name: 'ConfirmOrder',
            query: {
              type: 'shopProductPurchase',
              orderNo: shopProductPurchaseOrder.orderNo
            }
          })
        }).catch(() => {
        })

      }, function () {

      })
    },
    bannerTurn:function (item) {
      if (item.productId>0){
        this.$router.push({name:'ProductDetail',query:{id:item.productId,model:item.shopProductStockModel}})
      }
    },
    getBannerHeight:function () {
      return Math.ceil(this.getWinSize().width*0.5)
    },
    getProductList: function () {
      let $this = this
      if ($this.productListLoading || !$this.productListMore){
        return
      }
      var pageSize=20
      $this.productListLoading=true
      var page=Math.ceil($this.productList.length/20)+1
      $this.MyRequest($this.ApiDoNameMember + 'ShopProduct/getList', {page,pageSize}, function (data) {
        if (data.list.length===0){
          // $this.$message.success('商品加载完毕')
          $this.productListMore=false
          return
        }
        $this.productListLoading=false
        if (page>1){
          $this.productList=$this.productList.concat(data.list)
        }else{
          $this.productList=data.list
        }
        $this.$forceUpdate()
      }, function (msg) {
        $this.productListLoading=false
        $this.$message.error(msg)
        $this.$forceUpdate()
      })
    },
    changeCity: function () {
      // var wxPayPlus = api.require('wxPayPlus');
      // wxPayPlus.getOrderId({
      //   info: '购买可乐3瓶'
      // }, function(ret, err) {
      //   alert(JSON.stringify(ret))
      // });
      this.bus.$emit('ChangeCityDialogCallBus')
    },
    setBanner: function () {
      var swiper = new Swiper('.swiper-banner', {
        // 底部分页导航
        pagination: {
          el: '.swiper-pagination',
        },
        // 自动播放
        autoplay: {
          delay: 2000,
          stopOnLastSlide: false,
          disableOnInteraction: false,
        },
        // 切换效果:    默认=>滑动    fade=>渐入   cube=>盒子旋转  coverflow=>平面切换 flip=>平面翻转
        // effect : 'fade',
      })
    },
    checkUserStatus: function () {
      if (this.CurrUser.IsLogin()) {
        this.$router.push('/Center')
      } else {
        this.$router.push('/Login')
      }
    },
    getHomeData: function () {
      let $this = this
      $this.MyRequest($this.ApiDoNameMember + 'Public/home', {}, function (data) {
        // console.log('list',list)
        $this.brandList = data.brandList
        $this.bannerArr = data.bannerList
        $this.shopNums = data.shopNums
        $this.isSkill = data.isSkill
        $this.$set($this.dict,'CoverCity',data.CoverCity)
        localStorage.setItem('CoverCityCache',JSON.stringify(data.CoverCity))
        $this.$forceUpdate()
        setTimeout(function () {
          $this.setBanner()
        }, 1000)
      }, function (msg) {
        $this.$message.error(msg)
      })
    }
  }
}
</script>

